package com.example.microinvestcommon.util;

import jakarta.activation.DataHandler;
import jakarta.activation.FileDataSource;
import jakarta.annotation.PostConstruct;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.mail.Message;
import java.util.Date;
import java.util.Properties;

@Component
public class MailVerificationUtil {

    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;

    @Value("${spring.mail.port}")
    private String port;

    // 静态变量
    private static String staticHost;
    private static String staticUsername;
    private static String staticPassword;
    private static String staticPort;

    @PostConstruct
    public void init() {
        staticHost = host;
        staticUsername = username;
        staticPassword = password;
        staticPort = port;
    }

    /**
     * 发送邮件
     *
     * @param to             接收人邮箱
     * @param subject        邮件标题
     * @param content        邮件正文内容
     * @param imagePath      邮件内嵌图片路径（可选）
     * @param attachmentPath 邮件附件路径（可选）
     * @throws Exception
     */
    public static void sendMail(String to, String subject, String content, String imagePath, String attachmentPath) throws Exception {

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", staticHost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", staticPort);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.required", "false");
        props.put("mail.smtp.debug", "true");

        Session session = Session.getInstance(props);
        session.setDebug(true);

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(staticUsername, "Tianwailaiwu", "UTF-8"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to, "收件人昵称", "UTF-8"));
        message.setSubject(subject, "UTF-8");

        // ---- 正文部分 ----
        MimeBodyPart textPart = new MimeBodyPart();
        if (imagePath != null && !imagePath.isEmpty()) {
            textPart.setContent(content + "<br/><img src='cid:image001'/>", "text/html;charset=UTF-8");
        } else {
            textPart.setContent(content, "text/html;charset=UTF-8");
        }

        // ---- 图片部分（可选） ----
        MimeMultipart textImageMultipart = new MimeMultipart();
        textImageMultipart.addBodyPart(textPart);

        if (imagePath != null && !imagePath.isEmpty()) {
            MimeBodyPart imagePart = new MimeBodyPart();
            imagePart.setDataHandler(new DataHandler(new FileDataSource(imagePath)));
            imagePart.setContentID("image001");
            textImageMultipart.addBodyPart(imagePart);
        }

        textImageMultipart.setSubType("related");

        MimeBodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(textImageMultipart);

        // ---- 最终组合 ----
        MimeMultipart allMultipart = new MimeMultipart();
        allMultipart.addBodyPart(contentPart);

        if (attachmentPath != null && !attachmentPath.isEmpty()) {
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(new DataHandler(new FileDataSource(attachmentPath)));
            attachmentPart.setFileName(MimeUtility.encodeText("附件.doc"));
            allMultipart.addBodyPart(attachmentPart);
        }

        allMultipart.setSubType("mixed");

        message.setContent(allMultipart);
        message.setSentDate(new Date());
        message.saveChanges();

        Transport transport = session.getTransport();
        transport.connect(staticUsername, staticPassword);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}
